#include "same_check.h"
#include <cstring>
#include <math.h>
#include <stdio.h>
#define LENGTH(array) (sizeof(array) / sizeof(array[0]))
extern int Counter;
double calculate_cross_correlation(double *s1, double *s2, int n); //声明函数
// real_time_adc_data用来实时记录adc数据
extern double real_time_adc_data[250];
// recording_adc_data用来记录录音的adc数据
extern double recording_adc_data[250];
// adc_voltage用于存储ADC单次采样结果
extern double adc_voltage[3];
rt_uint8_t Greater_Threshold = 0;
rt_uint8_t Less_Than_Threshold = 0;
double same_check_once(void) {
  Greater_Threshold = Less_Than_Threshold = 0;
  for (char i = 0; i < LENGTH(recording_adc_data); i++) {
    //此处调节adc判断有声音的阈值
    if (real_time_adc_data[i] > 1.5 + (adc_voltage[2]-(3.3/2))) {
      Greater_Threshold += 1;
    } else if (real_time_adc_data[i] < 1.5 - (adc_voltage[2]-(3.3/2))) {
      Less_Than_Threshold += 1;
    }
    // rt_kprintf("real_time_adc_data[%d] = %.4f\r\n", i,
    // real_time_adc_data[i]);
  }
  //检测有多少大于或者少于阈值
  rt_kprintf("[test]big %d,less %d\r\n", Greater_Threshold,
             Less_Than_Threshold);
  if (Greater_Threshold < 10 && Less_Than_Threshold < 10) {
    //仅当声音波动大于x个，则认为有声音
    //关闭干扰
    HAL_TIM_PWM_Stop(&htim3, TIM_CHANNEL_1);
    HAL_GPIO_WritePin(GPIOB, GPIO_PIN_1, GPIO_PIN_SET);
    // //没声音时禁止识别
    rt_kprintf("no sound\r\n");
    return 0;
  } else {
    //识别到有声音,开启干扰
    HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_1);
    __HAL_TIM_SET_COMPARE(&htim3, TIM_CHANNEL_1, Counter / 2);
    HAL_GPIO_WritePin(GPIOB, GPIO_PIN_1, GPIO_PIN_RESET);
  }

  return calculate_cross_correlation(real_time_adc_data, recording_adc_data,
                                     LENGTH(recording_adc_data));
  //  rt_kprintf("pxy = %.4f\r\n", pxy);
}

/* 返回值在区间： [-1,1]          */
/* 如返回-10，则证明输入参数无效    */
#define delta 0.0001f
/**
 * 计算两个时间序列的交叉相关系数(相关性)
 * @param s1 第一个时间序列的指针
 * @param s2 第二个时间序列的指针
 * @param n 时间序列的长度(数组大小)
 * @return 交叉相关系数，如果计算失败则返回-10
 */
double calculate_cross_correlation(double *s1, double *s2, int n) {
  double sum_s12 = 0.0;
  double sum_s1 = 0.0;
  double sum_s2 = 0.0;
  double sum_s1s1 = 0.0; // s1^2
  double sum_s2s2 = 0.0; // s2^2
  double pxy = 0.0;
  double temp1 = 0.0;
  double temp2 = 0.0;
  // rt_kprintf("scalculate_cross_correlation\r\n");
  if (s1 == NULL || s2 == NULL || n <= 0)
    return -10;

  for (int i = 0; i < n; i++) {
    sum_s12 += s1[i] * s2[i];
    sum_s1 += s1[i];
    sum_s2 += s2[i];
    sum_s1s1 += s1[i] * s1[i];
    sum_s2s2 += s2[i] * s2[i];
  }

  temp1 = n * sum_s1s1 - sum_s1 * sum_s1;
  temp2 = n * sum_s2s2 - sum_s2 * sum_s2;

  /* 分母不可为0 */
  if ((temp1 > -delta && temp1 < delta) || (temp2 > -delta && temp2 < delta) ||
      (temp1 * temp2 <= 0)) {
    return -10;
  }

  pxy = (n * sum_s12 - sum_s1 * sum_s2) / sqrt(temp1 * temp2);

  return pxy;
}